/**
 * 现金支付接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');
//redis
let db, redis;

//cashPay接口入口文件
let index = function(getData, postData, config, _redis, _db) {
	let deferred = Q.defer();
	db = _db
	redis = _redis;
	if(postData.payGoods && postData.attachGoods && postData.tableNum) {
		let storeData, userId, payGoodsOrderData, attachGoodsData, orderData, insertOrderData;
		let {storeId, payGoods, attachGoods, tableNum, _3rdSession} = postData;
		getUserId(_3rdSession).then(function(_userId) {
			userId = _userId;
			return db.select('storeOrder', {
				userId: userId,
				payMode: 'cashPay',
				userPayed: false
			});
		}, function() {
			//获取用户ID失败
			deferred.reject('-0081');
		}).then(function(notPayOrderList) {
			if(notPayOrderList.length > 0) {
				//返回未支付的订单列表
				deferred.resolve(notPayOrderList);
			}
			else {
				//获取商户数据
				return getStoreData('-0040');
			}
		}, function() {
			//查询未现金支付订单用户失败
			deferred.reject('-0186');
		}).then(function(_storeData) {
			storeData = _storeData;
			return getPayGoodsData(payGoods);
		}, function() {
			//获取商户数据失败
			deferred.reject('-0040');
		}).then(function(_payGoodsOrderData) {
			payGoodsOrderData = _payGoodsOrderData;
			return getAttachGoodsData(attachGoods);
		}, function(errCode) {
			//获取支付的菜品数据失败
			deferred.reject(errCode);
		}).then(function(_attachGoodsData) {
			attachGoodsData = _attachGoodsData;
			return createOrder(payGoods, payGoodsOrderData, attachGoodsData);
		}, function() {
			//获取购买的附加物品数据失败
			deferred.reject('-0118');
		}).then(function(_orderData) {
			orderData = _orderData;
			return util.createRandomStr(24);
		}, function(errCode) {
			//生成菜品订单失败
			deferred.reject(errCode);
		}).then(function(orderId) {
			orderId = storeId + '-' + orderId;
			insertOrderData = {
				storeId: storeId,
				storeName: storeData.storeName,
				orderId: orderId,
				userId: userId,
				tableNum: tableNum,
				goodsList: orderData,
				timestamp: parseInt(Date.now() / 1000),
				payMode: 'cashPay',
				orderDone: false,
				userPayed: false,
				storeReceiveMoney: false
			};
			return db.insert('storeOrder', insertOrderData);
		}, function() {
			//生成订单号失败
			deferred.reject('-0085');
		}).then(function() {
			deferred.resolve(['echo', JSON.stringify({
				errCode: '0',
				data: {
					orderId: insertOrderData.orderId
				}
			}), 'broadcast', {
				storeId: storeId,
				type: 'sys',
				event: 'orderPayDone',
				data: insertOrderData
			}]);
		}, function() {
			//新增现金支付订单失败
			deferred.reject('-0187');
		});
	}
	return deferred.promise;
}

//获取支付的物品数据
let getPayGoodsData = function(payGoods) {
	let deferred = Q.defer();
	//预定义一个进行or查询的数组变量	
	let payGoodsList = [];
	//遍历支付的物品列表
	for(let goodsIndex in payGoods) {
		//往正式支付的物品列表中添加菜品ID
		payGoodsList.push({
			foodId: payGoods[goodsIndex].foodId
		});
		//判断遍历是否完成
		if(goodsIndex == payGoods.length - 1) {
			db.select('foodMenu', {
				$or: payGoodsList
			}).then(function(payGoodsData) {
				deferred.resolve(payGoodsData);
			}, function() {
				deferred.reject('-0063');
			});
		}
	}
	return deferred.promise;
}

let getAttachGoodsData = function(attachGoods) {
	let deferred = Q.defer();
	//预定义一个进行or查询的数组变量	
	let attachGoodsList = [];

	if(attachGoods.length == 0) {
		deferred.resolve([]);
	}

	//遍历支付的附加物品列表
	for(let goodsIndex in attachGoods) {
		//往正式支付的物品列表中添加菜品ID
		attachGoodsList.push({
			goodsId: attachGoods[goodsIndex].goodsId
		});
		//判断遍历是否完成
		if(goodsIndex == attachGoods.length - 1) {
			db.select('attachGoods', {
				$or: attachGoodsList
			}).then(function(attachGoodsData) {
				deferred.resolve(attachGoodsData);
			}, function() {
				deferred.reject('-0063');
			});
		}
	}
	return deferred.promise;
}

//创建订单函数
let createOrder = function(payGoodsList, payGoodsOrderList, attachGoodsData) {
	let deferred = Q.defer();
	console.log('处理附加物品', attachGoodsData);
	//存放错误的菜品列表
	let errorGoodsOrder = [];
	let orderList = [];
	//判断提交的订单信息中是否包含了不存在的菜品
	if(payGoodsList.length != payGoodsOrderList.length) {
		//用于判断是否找到对应的支付物品
		let goodsFound = false;
		//遍历检查是哪个菜品出现问题
		for(let goodsIndex in payGoodsList) {
			//如果只有一个菜品，那么直接将这个物品推入错误列表
			if(payGoodsOrderList.length == 1) {
				errorGoodsOrder.push(payGoodsList[goodsIndex]);
			}
			else {
				for(let goodsOrderIndex in payGoodsOrderList) {
					if(payGoodsOrderList[goodsOrderIndex].foodId == payGoodsList[goodsIndex].foodId) {
						//设置找到了对应菜品
						goodsFound = true;
					}
					else if(goodsOrderIndex == payGoodsOrderList.length - 1 && goodsFound == false) {
						//出错的菜品
						errorGoodsOrder.push(payGoodsList[goodsIndex].foodId);
					}
				}
				//重置
				goodsFound = false;
			}
			//判断是否遍历完毕
			if(goodsIndex == payGoodsList.length - 1) {
				//如果不存在任何一个错误的菜品则返回错误
				if(errorGoodsOrder.length == 0) {
					//订单中可能存在重复菜品ID
					deferred.reject('-0084');
				}
				else {
					//返回菜品列表异常
					deferred.resolve({
						status: -1,
						data: errorGoodsOrder
					});
				}
			}
		}
		
	}
	else {
		//遍历支付的菜品列表与数据库的菜品列表判断是否下架或缺货
		for(let goodsIndex in payGoodsList) {
			for(let goodsOrderIndex in payGoodsOrderList) {
				if(payGoodsList[goodsIndex].foodId == payGoodsOrderList[goodsOrderIndex].foodId) {
					if(payGoodsOrderList[goodsOrderIndex].foodStatus == 'pulled' || (payGoodsOrderList[goodsOrderIndex].foodStock != -1 && payGoodsList[goodsIndex].count >= payGoodsOrderList[goodsOrderIndex].foodStock)) {
						errorGoodsOrder.push(payGoodsList[goodsIndex].foodId);
					}
					else {
						//往订单列表添加订单
						orderList.push({
							//菜品ID
							foodId: payGoodsOrderList[goodsIndex].foodId,
							//菜品名称
							foodName: payGoodsOrderList[goodsIndex].foodName,
							//菜品价格
							foodPrice: payGoodsOrderList[goodsIndex].foodPrice,
							//点选的菜品数量
							count: payGoodsList[goodsIndex].count
						});
					}
				}
			}
			//判断是否遍历到了最后一个
			if(goodsIndex == payGoodsList.length - 1) {
				if(attachGoodsData.length == 0) {
					//如果有菜品下架或缺货则返回-2
					if(errorGoodsOrder.length > 0) {
						deferred.resolve({
							status: -2,
							data: errorGoodsOrder
						});
					}
					else {
						//订单正确返回需要支付的列表
						deferred.resolve(orderList);
					}
				}
				for(let attachGoodsIndex in attachGoodsData) {
					orderList.push({
						//附加物品ID
						goodsId: attachGoodsData[attachGoodsIndex].goodsId,
						//附加物品名称
						goodsName: attachGoodsData[attachGoodsIndex].goodsName,
						//附加物品单价
						goodsPrice: attachGoodsData[attachGoodsIndex].goodsPrice,
						//附加物品数量
						goodsCount: attachGoodsData[attachGoodsIndex].goodsCount
					});
					if(attachGoodsIndex == attachGoodsData.length - 1) {
						//如果有菜品下架或缺货则返回-2
						if(errorGoodsOrder.length > 0) {
							deferred.resolve({
								status: -2,
								data: errorGoodsOrder
							});
						}
						else {
							//订单正确返回需要支付的列表
							deferred.resolve(orderList);
						}
					}
				}
			}
		}
	}
	return deferred.promise;
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		if(data) {
			data = JSON.parse(data);
			if(data.openId) {
				deferred.resolve(data.openId);
			}
			else {
				deferred.reject();
			}
		}
		else {
			deferred.reject();
		}
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

//获取商户数据函数
let getStoreData = function() {
	let deferred = Q.defer();
	db.select('storeInfo', {}).then(function(storeInfo) {
		let storeData = {};
		let storeInfoKey = '';
		if(storeInfo.length == 0) {
			deferred.resolve(storeData);
		}
		else {
			for(let infoIndex in storeInfo) {
				for(let storeInfoKey in storeInfo[infoIndex]) {
					if(storeInfoKey != '_id') {
						storeData[storeInfoKey] = storeInfo[infoIndex][storeInfoKey];
						if(infoIndex == storeInfo.length - 1) {	
							console.log(storeData);
							deferred.resolve(storeData);
						}
					}
				}
			}
		}
	}, function() {
		deferred.reject();
	});
	return deferred.promise;	
}

//暴露接口
module.exports = {
	index: index
}